<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef,watch , defineExpose} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
  name: "wangeditor-util",
  components: { Editor, Toolbar },
  props: {
    showToolbar: {
      type: Boolean,
      default: true
    },
    editorHeight: {
      type: String,
      default: '56rem'
    },
    readonly: {
      type: Boolean,
      default: false
    },
    borderPx: {
      type: String,
      default: '1px'
    },
    sectionValue: {
      // TODO: 完成后改为 true
      required: false,
      type: String,
      default:"{'title':'文章标题','content':'文章内容'}"
    }
  },
  setup(props) {
    // console.log(props.sectionValue)
    // const { getxxx } = inject("getxxx")
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    // 内容 HTML
    //传入的数据
    const valueHtml = ref(props.sectionValue)
    //传回的数据
    let contentHtml = ref("")
    // console.log(valueHtml.value)
    watch(valueHtml,(newVal,oldVal)=>{
      contentHtml.value = newVal
      // getxxx(contentHtml.value)
    })
    function fxxx() {
      return contentHtml.value
    }
    // 自定义事件传值

    function emitContent(){
      emit('content-wangEditor',contentHtml.value)
    }

    // const content = ref(props.sectionValue)

    // const editor = createEditor({
    //
    //   // 其他属性
    // })

    // 模拟 ajax 异步获取内容
    // onMounted(() => {
    //   setTimeout(() => {
    //     valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    //   }, 1500)
    // })

    //工具栏配置
    const toolbarConfig = {

    }
    //编辑器配置
    const editorConfig = {
      placeholder: '请输入内容...',
      readOnly: props.readonly
    }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      // 记录 editor 实例，重要！
      editorRef.value = editor
    }
    defineExpose({
      fxxx
    })
    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      fxxx
    };
  }
}
</script>

<template>
  <div :style="{border: borderPx+' solid #ccc'}">
    <Toolbar
        v-if="showToolbar"
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        :style="{'min-height': '72vh','overflow-y': 'hidden'}"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
    />
  </div>
</template>

<style lang="scss" scoped>

</style>
